package controllers

import (
    "git.oschina.net/hfwb/tianqi.git/tq/model"
    "crypto/md5"
    "fmt"
    "errors"
    "strings"
)

type Staff struct {
    base
}

func (this *Staff) List() {
    this.menuList.User.Open = true
    if list, err := model.NewStaff().GetAll(); err != nil {
        this.AlertError(err.Error())
    } else {
        this.Data["list"] = list
    }
    this.TplName = "staff.list.tpl"
}

func (this *Staff) Edit() {
    this.SetTitle("添加员工")
    this.menuList.User.Open = true

    staffId, _ := this.GetInt64("id")
    sf := model.NewStaff()
    this.Data["model"] = sf
    if staffId != 0 {
        if err := sf.GetById(staffId); err != nil {
            this.AlertError(err.Error())
        }
    }

    if (this.Ctx.Request.Method == "POST") {
        if err := this.save(sf); err != nil {
            this.AlertError(err.Error())
        } else {
            this.AlertSuccess("保存成功")
        }
    }
    this.TplName = "staff.edit.tpl"
}

func (this *Staff) save(sf *model.Staff) error {
    sf.Username = this.GetString("username")
    sf.Username = strings.TrimSpace(sf.Username)
    if sf.Username == "" {
        return errors.New("请输入用户名")
    }
    sf.Phone = this.GetString("phone")
    sf.Password = this.GetString("password")

    old, err := sf.GetByName(sf.Username)
    if err != nil {
        return err
    }
    if old != nil && old.StaffId != sf.StaffId {
        return errors.New("用户名已经存在")
    }

    if sf.Password != "" {
        sf.Password = fmt.Sprintf("%x", md5.Sum([]byte(sf.Password)))
    }
    if sf.StaffId == 0 && sf.Password == "" {
        return errors.New("请设置密码")
    }
    if sf.StaffId != 0 {
        setPassword := true
        if sf.Password == "" {
            setPassword = false
        }
        return sf.Update(setPassword)
    } else {
        return sf.Add()
    }
}